package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JSONUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.entity.*;
import top.littlejiang.onlinexam.mapper.OlexamExamPaperMapper;
import top.littlejiang.onlinexam.service.OlexamExamPaperService;
import top.littlejiang.onlinexam.service.OlexamExamService;
import top.littlejiang.onlinexam.service.OlexamQuestionsService;
import top.littlejiang.onlinexam.service.OlexamStuScoreService;
import top.littlejiang.onlinexam.vo.PaperQueryVO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 试卷表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-11
 */
@Service
public class OlexamExamPaperServiceImpl extends BaseServiceImpl<OlexamExamPaperMapper, OlexamExamPaper> implements OlexamExamPaperService {

    @Autowired
    OlexamExamService examService;
    @Autowired
    OlexamQuestionsService questionsService;
    @Autowired
    OlexamStuScoreService scoreService;

    /**
     * 查找试卷
     *
     * @param paperQuery
     * @return
     */
    @Override
    public List<OlexamExamPaper> getList(PaperQueryVO paperQuery) {
        List<OlexamExamPaper> rst = new ArrayList<>();
        if (!StringUtils.isBlank(paperQuery.getFkCourseName())){
            QueryWrapper<OlexamCourse> courseWrapper = new QueryWrapper<>();
            courseWrapper.eq("course_name", paperQuery.getFkCourseName());
            rst = baseMapper.getListByCourse(paperQuery.getPaperName(), paperQuery.getFkCourseName());
        } else {
            QueryWrapper<OlexamExam> examWrapper = new QueryWrapper<>();
            examWrapper.eq("exam_name", paperQuery.getFkExamName());
            rst = baseMapper.getListByExam(paperQuery.getPaperName(), paperQuery.getFkExamName());
        }
        return rst;
    }

    /**
     * 增加或更新试卷
     *
     * @param examPaper
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertOrUpdate(OlexamExamPaper examPaper) {
        if (examPaper.getId() == 0){
            examPaper.setId(null);
        }
        examPaper.setUpdateTime(DateUtils.getTime())
                .setCreateUser(JWTUtils.getUserId())
                .setFkExamUuid(examService.getUuidByNames(examPaper.getFkExamName()));
        saveOrUpdate(examPaper);
    }

    /**
     * 根据考试uuid 逻辑删除
     *
     * @param uuids
     */
    @Override
    public void deleteByUuid(List<String> uuids) {
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.set("is_del", 1);
        wrapper.in("fk_exam_uuid", uuids);
        this.update(wrapper);
    }

    /**
     * 获取一张试卷
     *
     * @param exam
     * @return
     */
    @Override
    public List<OlexamQuestions> getByUuid(OlexamExam exam) {
        QueryWrapper wrapper = new QueryWrapper();
        List<OlexamQuestions> questionsList = new ArrayList<>();
        OlexamExamPaper paper;
        OlexamStuScore stuScore1 = scoreService.queryOne(exam.getExamUuid(), JWTUtils.getUserId());
        if (Objects.isNull(stuScore1)){
            wrapper.eq("fk_exam_uuid", exam.getExamUuid());
            wrapper.eq("is_del", 0);
            List<OlexamExamPaper> paperList = list(wrapper);

            if (exam.getIsAfewRandow() == 1 && paperList.size() > 0){
                paper = paperList.get((int)(Math.random()*paperList.size()));
            }else{
                paper = paperList.get(0);
            }
            OlexamStuScore stuScore = new OlexamStuScore();
            stuScore.setFkExamUuid(exam.getExamUuid())
                    .setFkUserId(JWTUtils.getUserId())
                    .setIsCorrected(0)
                    .setFkPaperId(paper.getId());
            scoreService.getBaseMapper().insert(stuScore);
        }else{
            paper = getBaseMapper().selectById(stuScore1.getFkPaperId());
        }
        List<Serializable> questionIds = JSONUtils.jsonToList(paper.getQuestionList(), Serializable.class);
        questionsList = questionsService.selectInIds(questionIds, false);
        return questionsList;
    }
}
